<!DOCTYPE html>
<html>
<head>
  <title>React</title>
  <meta charset="UTF-8">
  <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
  <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
  <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="root">
</div>

<script type="text/babel">
    let _state = [];
    let index = 0

    function herBoysState(initialValue) {
        //保存当前下的index
        let currentIndex = index
        _state[index] = _state[index] || initialValue
        //利用闭包保存函数
        const setState = (newValue) => {
            //更新state值，
            _state[currentIndex] = newValue;
            render(); //触发重新渲染
        };
        index += 1;// 每次更新完state值后，index值+1
        return [_state[currentIndex], setState];
    }

    const render = () => {
        index = 0;	//必须在渲染前后将index值重置为0，不然index会一种增加1
        ReactDOM.render(<App/>, document.getElementById("root"));
    };
    const App = () => {
        const [count, setCount] = herBoysState(1)
        const [age, setAge] = herBoysState(0)
        return <div>
            <div>
                <p>{count}</p>
                <button onClick={() => {
                    setCount(count + 1)
                }}>setCount
                </button>
            </div>
            <div>
                <p>{age}</p>
                <button onClick={() => {
                    setAge(age + 1)
                }}>setCount
                </button>
            </div>
        </div>
    };
    ReactDOM.render(<App/>, document.getElementById("root"));
</script>
</body>

</html>

